package simple;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;
import util.Log;

import java.nio.charset.StandardCharsets;

public class MyHandler01 extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Log.i("服务器线程：" + Thread.currentThread().getName());
        //ctx上下文信息 可以拿到 管道和通道
        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] buff = new byte[byteBuf.readableBytes()];
        byteBuf.getBytes(0, buff);
        Log.i("收到客户端信息：" + new String(buff));

        super.channelRead(ctx, msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        SocketChannel socketChannel = (SocketChannel) ctx.channel();
        socketChannel.writeAndFlush(Unpooled.copiedBuffer("收到消息".getBytes(StandardCharsets.UTF_8)));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.channel().close();
    }
}
